package com.amoyt.project.service.admin.impl;

import com.amoyt.project.config.redis.RedisCache;
import com.amoyt.project.config.redis.RedisIdWork;
import com.amoyt.project.constants.IdConstants;
import com.amoyt.project.constants.RedisConstants;
import com.amoyt.project.domain.bo.LoginUser;
import com.amoyt.project.domain.dto.insert.ArticleAddDto;
import com.amoyt.project.domain.dto.query.ArticlePageQuery;
import com.amoyt.project.domain.dto.update.ArticleUpdateDto;
import com.amoyt.project.domain.pojo.Article;
import com.amoyt.project.domain.pojo.ArticleContentBlock;
import com.amoyt.project.domain.res.PageResult;
import com.amoyt.project.domain.res.Result;
import com.amoyt.project.domain.vo.NewsDetailVo;
import com.amoyt.project.mapper.ArticleContentBlockMapper;
import com.amoyt.project.mapper.ArticleMapper;
import com.amoyt.project.service.admin.ArticleService;
import com.amoyt.project.utils.ConvertBeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Date: 2025/8/25
 * @Time: 16:18
 * @Author: TQ_QT
 * @Description:
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleContentBlockMapper contentMapper;
    @Autowired
    private RedisIdWork redisIdWork;
    @Autowired
    private RedisCache redisCache;

    @Override
    public Result list(ArticlePageQuery query) {
        //查询返回即可
        IPage<Article> page = new Page<>(query.getPage(), query.getPageSize());

        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(query.getArticleTitle()), "article_title", query.getArticleTitle());
        queryWrapper.like(StringUtils.isNotBlank(query.getPublisherName()), "publisher_name", query.getPublisherName());
        queryWrapper.eq(query.getCategory() != null, "category", query.getCategory());
        queryWrapper.eq(query.getIsOpen() != null, "is_open", query.getIsOpen());
        queryWrapper.between(query.getStartTime() != null && query.getEndTime() != null, "publish_time", query.getStartTime(), query.getEndTime());

        IPage<Article> articles = articleMapper.selectPage(page, queryWrapper);

        PageResult pageResult = PageResult.builder()
                .total(articles.getTotal())
                .records(articles.getRecords())
                .build();

        return Result.success(pageResult);
    }

    @Override
    public Result queryArticleDetail(String articleId) {

        //构造条件
        QueryWrapper<ArticleContentBlock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id",articleId);

        //查询详情
        List<ArticleContentBlock> contentBlocks = contentMapper.selectList(queryWrapper);

        //处理顺序（根据sort_num，从小到大排列列表）
        contentBlocks.sort(new Comparator<ArticleContentBlock>() {
            @Override
            public int compare(ArticleContentBlock o1, ArticleContentBlock o2) {
                //数字小，在前面
                return o1.getSortNum() - o2.getSortNum();
            }
        });

        return Result.success(contentBlocks);
    }

    @Override
    @Transactional
    public Result add(Integer flag, ArticleAddDto articleAddDto) {
        //校验参数

        //当前账号
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //整理数据，进行添加
        Article article = ConvertBeanUtils.convert(articleAddDto, Article.class);
        //生成id
        String articleId = IdConstants.ARTICLE_ID_PREFIX + redisIdWork.nextId(IdConstants.ARTICLE_ID_PREFIX);
        article.setArticleId(articleId);
        article.setCreateBy(loginUser.getUser().getUserId());
        article.setCreateTime(LocalDateTime.now());
        article.setIsPublished(1);
        article.setPublisherId(loginUser.getUser().getUserId());
        article.setPublisherName(loginUser.getUser().getRealName());
        article.setPublishUnit(articleAddDto.getPublisherUnit());
        article.setPublishTime(LocalDateTime.now());

        //处理内容块
        if (articleAddDto.getContentBlockList() == null || articleAddDto.getContentBlockList().size() <= 0){
            throw new IllegalArgumentException("内容块不能为空");
        }

        List<ArticleContentBlock> contentBlocks = ConvertBeanUtils.convertList(articleAddDto.getContentBlockList(), ArticleContentBlock.class);
        //给每一个设置文章id,产生时间等
        contentBlocks.forEach(contentBlock -> {
            contentBlock.setArticleId(articleId);
            contentBlock.setCreateTime(LocalDateTime.now());
            contentBlock.setDeleted(0);
        });

        articleMapper.insert(article);
        contentMapper.insertList(contentBlocks);

        //删除缓存
        redisCache.deleteObject(RedisConstants.CACHE_ARTICLE_DATA);

        return Result.success(articleId);
    }

    @Override
    @Transactional
    public Result deleteBatch(List<String> articleIds) {
        //文章
        articleMapper.deleteBatchIds(articleIds);

        //内容块
        QueryWrapper<ArticleContentBlock> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("article_id",articleIds);

        contentMapper.delete(queryWrapper);

        //删除缓存
        redisCache.deleteObject(RedisConstants.CACHE_ARTICLE_DATA);
        return Result.success();
    }

    @Override
    @Transactional
    public Result updateArticle(ArticleUpdateDto articleUpdateDto) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //复制数据
        Article article = ConvertBeanUtils.convert(articleUpdateDto, Article.class);
        article.setUpdateBy(loginUser.getUser().getUserId());
        article.setUpdateTime(LocalDateTime.now());

        List<ArticleContentBlock> contentBlocks = ConvertBeanUtils.convertList(articleUpdateDto.getContentBlockList(), ArticleContentBlock.class);
        contentBlocks.forEach(contentBlock -> {
            contentBlock.setUpdateTime(LocalDateTime.now());
            contentBlock.setArticleId(article.getArticleId());
        });

        //找到本次需要删除的内容块id
        List<String> deleteIds = articleUpdateDto.getContentBlockList().stream()
                .filter(contentBlock -> contentBlock.getDelFlag()!=null)
                .map(contentBlock -> contentBlock.getBlockId())
                .collect(Collectors.toList());

        //删除相应内容块
        contentMapper.deleteBatchIds(deleteIds);

        //移除contentBlocks中包含deleteIds的部分
        contentBlocks.removeIf(contentBlock -> deleteIds.contains(contentBlock.getBlockId()));

        //更新
        articleMapper.updateById(article);
        contentMapper.updateBatchById(contentBlocks);

        return Result.success();
    }

    @Override
    public Result queryArticleDetailNew(String articleId) {


        Article article = articleMapper.selectById(articleId);

        NewsDetailVo newsVo = ConvertBeanUtils.convert(article, NewsDetailVo.class);

        //构造条件
        QueryWrapper<ArticleContentBlock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id",articleId);

        //查询详情
        List<ArticleContentBlock> contentBlocks = contentMapper.selectList(queryWrapper);

        //处理顺序（根据sort_num，从小到大排列列表）
        contentBlocks.sort(new Comparator<ArticleContentBlock>() {
            @Override
            public int compare(ArticleContentBlock o1, ArticleContentBlock o2) {
                //数字小，在前面
                return o1.getSortNum() - o2.getSortNum();
            }
        });

        newsVo.setContentBlocks(contentBlocks);

        return Result.success(newsVo);
    }
}
